package com.liu.tcpDemo.Server;

import com.alibaba.fastjson.JSONObject;

import java.io.ObjectInputStream;
import java.net.Socket;

/*监听请求的类，需要多线程所以实现Runnable*/
public class ServletListen implements Runnable{
    private Socket socket;
//    构造函数初始化socket连接
    ServletListen(Socket socket){
        this.socket=socket;
    }
    @Override
    public void run() {
//      用输入流接收客户端的信息
        ObjectInputStream ois=null;
        try {
//            流操作
            ois=new ObjectInputStream(socket.getInputStream());
            while (true){
                MsgEntity msgEntity=new MsgEntity();
                JSONObject jsonObject =(JSONObject) ois.readObject();
                if (jsonObject.get("type").equals("msg")){
                    System.out.println("来自客户端的消息："+jsonObject.get("chat"));
                    System.out.println("请输入");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
//            最后关闭资源
            try {
                ois.close();
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
